package com.heimali.happyreader.wraper;

import java.net.URI;
import java.util.ArrayList;

import com.heimali.happyreader.Statics;
import com.heimali.happyreader.config.Constants;
import com.heimali.happyreader.db.dao.ListDao;
import com.heimali.happyreader.http.JsonParser;
import com.heimali.happyreader.model.Intro;
import com.heimali.happyreader.utils.HttpUtils;

public class ArticleListWraper extends BaseWraper {
	public static final String TAG = "ArticleListWraper";
	public static final int TYPE_RECENT = 1;
	public static final int TYPE_EARLY = 2;
	public static enum TYPES {
		TYPE_RECENT, TYPE_EARLY
	};
	
	public ArticleListWraper(URI uri, Callback callback) {
		super(uri, callback);
	}

	public ArticleListWraper(Callback callback) {
		this(TYPES.TYPE_RECENT, callback);
	}
	
	public ArticleListWraper(TYPES type, Callback callback) {
		int lastID = -1;
		String intf = Constants.listUpdateRecentIntfPath;
		if (type == TYPES.TYPE_RECENT) {
//			lastID = new ListDao().queryMaxArticleID();
			lastID = 0;
		}else {
			lastID = new ListDao().queryMinArticleID();
			intf = Constants.listUpdateEarlyIntfPath;
		}
		
		String query = HttpUtils.buildQuery(new String[] { "id", Statics.getUid() },
				new String[] { "last_id", String.valueOf(lastID) },
				new String[] { "token", Statics.getToken() });
		this.uri = HttpUtils.buildURI(intf, query);
		this.callback = callback;
	}

	@Override
	protected void onExecute(String result) {
		try {
			ArrayList<Intro> intros = JsonParser.listParser(result);
			if (intros == null) {
				callback.onFail(Constants.E_SERVER_BUSY, null);
				return;
			}

			callback.onSuccess(intros);

		} catch (Exception e) {
			callback.onFail(Constants.E_UNKNOWN_ERROR, e.getMessage());
		}
	}

}
